package cn.huiyunche.driver.schedule;

import cn.huiyunche.base.service.constant.OtmUrlConstant;
import cn.huiyunche.base.service.constant.TmsUrlConstant;
import cn.huiyunche.base.service.enums.DWaybillStatusEnum;
import cn.huiyunche.base.service.enums.TmsUrlTypeEnum;
import cn.huiyunche.base.service.interfaces.TmsOrderCallHistoryService;
import cn.huiyunche.base.service.utils.DateUtils;
import cn.huiyunche.base.service.vo.OrderConfirmResult;
import cn.huiyunche.driver.service.OrderService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import cn.huiyunche.tools.basic.Collections3;


/**
 * 确认回单定时任务
 *
 * @author hdy
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class OrdersConfirmQuartzCluster implements Job, Serializable {

    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = 1L;
    private static final Logger logger = LoggerFactory.getLogger(OrdersConfirmQuartzCluster.class);

	/*@Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
		logger.info("jbo start: confirm orders job time: {}", new DateTime().toString(DateUtils.YYYY_MM_DD_HH_MM_SS_SSS));
        final String url = TmsUrlConstant.PULL_ORDER_CONFIRM;
        TmsOrderCallHistoryService tmsOrderCallHistoryService = QuartzClusterFactory.getTmsOrderCallHistoryService();
        //查询上一次成功url调用成功的记录
        Date lastTime = tmsOrderCallHistoryService.getLastTimeSuccess(TmsUrlTypeEnum.PULL_ORDER_CONFIRM.getValue(), true);

        Map paramsMap = new HashedMap();
        paramsMap.put("lastTime", new DateTime(lastTime).toString(DateUtils.YYYY_MM_DD_HH_MM_SS_SSS));

        String result = tmsOrderCallHistoryService.urlCall(url, TmsUrlTypeEnum.PULL_ORDER_CONFIRM.getValue(), paramsMap);
        logger.info("zl confirm order finish job result : {}.", result);
        if(StringUtils.isNotBlank(result)){
            JSONObject jsonObject = JSONObject.parseObject(result);
            String data = jsonObject.getString("data");
            if(StringUtils.isNotBlank(data)){
                List<OrderConfirmResult> confirmResults = JSONArray.parseArray(data, OrderConfirmResult.class);
                if(CollectionUtils.isNotEmpty(confirmResults)){
                	OrderService orderService = QuartzClusterFactory.getOrderService();
                    orderService.confirmResults(confirmResults);
                }
            }
        }
        logger.info("jbo end: confirm orders job time: {}", new DateTime().toString(DateUtils.YYYY_MM_DD_HH_MM_SS_SSS));

	}*/

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        logger.info("jbo start: confirm orders job time: {}", new DateTime().toString(DateUtils.YYYY_MM_DD_HH_MM_SS_SSS));
         OrderService orderService = QuartzClusterFactory.getOrderService();
         List<String> iorderids = orderService.getOrderLineIdListByStatus(Arrays.asList(DWaybillStatusEnum
                .EXCEPTION_CONFIRM.getValue(), DWaybillStatusEnum.DEAL_CAR.getValue(), DWaybillStatusEnum.COMPLETED.getValue()));

        if(CollectionUtils.isEmpty(iorderids)){
            logger.info("获取数据库中待回单数据【iorderids】为空 : {}，直接结束任务", iorderids);
            return;
        }

        //错误使用方法
        //Map<String, Object> paramsMap = null;

        Map<String, Object> paramsMap = new HashedMap<>();

        List<List<String>> partitionList= Lists.partition(iorderids,20);

        for(int i=0;i<partitionList.size();i++){

            List<String> isubOrderid =partitionList.get(i);

            String sb=Collections3.convertToString(isubOrderid,",");

            if (StringUtils.isBlank(sb)) {
                logger.info("获取数据库中待回单数据【isubOrderid】为空 : {}，直接结束任务", isubOrderid);
                return;
            }

            paramsMap.put("iorderids",sb);

//            final String url = TmsUrlConstant.PULL_ORDER_CONFIRM2;
            final String url = OtmUrlConstant.PULL_ORDER_CONFIRM;
            TmsOrderCallHistoryService tmsOrderCallHistoryService = QuartzClusterFactory.getTmsOrderCallHistoryService();
            String result = tmsOrderCallHistoryService.urlCall(url, TmsUrlTypeEnum.PULL_ORDER_CONFIRM.getValue(), paramsMap, 30000);
            logger.info("zl confirm order finish job result : {}.", result);

            if (StringUtils.isNotBlank(result)) {
                JSONObject jsonObject = JSONObject.parseObject(result);
                String data = jsonObject.getString("data");
                if (StringUtils.isNotBlank(data)) {
                    JSONArray objects = JSONObject.parseArray(data);
                    List<OrderConfirmResult> confirmResults =new ArrayList<>();
                    for (int j = 0; j<objects.size();j++) {
                       if (StringUtils.isNotBlank(objects.getJSONObject(j).getString( "DTRETURN"))) {
                           OrderConfirmResult ocr = new OrderConfirmResult();
                           ocr.setOrdercost(objects.getJSONObject(j).getString("ordercost"));
                           ocr.setIlineid(objects.getJSONObject(j).getString("ILINEID"));
                           ocr.setVcorderno(objects.getJSONObject(j).getString("VCORDERNO"));
                           Date date = null;
                           try {
                               SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.OTM_FORMAT_DATETIME);
                               date = sdf.parse(objects.getJSONObject(j).getString("DTRETURN"));
                           } catch (ParseException e) {
                               e.printStackTrace();
                           }
                           ocr.setDtreturn(date);
                           confirmResults.add(ocr);
                       }
                    }
                    // List<OrderConfirmResult> confirmResults = JSONArray.parseArray(data, OrderConfirmResult.class);
                    if (CollectionUtils.isNotEmpty(confirmResults)) {
                        orderService.confirmResults(confirmResults);
                    }
                }
            }
        }

        //释放hashmap
        paramsMap.clear();

        logger.info("jbo end: confirm orders job time: {}", new DateTime().toString(DateUtils.YYYY_MM_DD_HH_MM_SS_SSS));


    }

}
